//
//  QuTask.swift
//  
//
//  Created by Hoa on 2021/1/4.
//

import Foundation

public struct QuTask {
    
    public let time: TimeInterval
    
    public typealias Task = (_ cancel: Bool) ->()
    public func delay(task: @escaping ()->()) -> Task? {
        func dispatch_later(block: @escaping ()->()) {
            let t = DispatchTime.now() + time
            DispatchQueue.main.asyncAfter(deadline: t, execute: block)
        }
        var closure: (()->())? = task
        var result: Task?
        let delayedClosure: Task = { cancel in
            if let internalClosure = closure {
                if cancel == false {
                    DispatchQueue.main.async(execute: internalClosure)
                }
            }
            closure = nil
            result = nil
        }
        result = delayedClosure
        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(false)
            }
        }
        return result
    }
    
    public static func cancel(_ task: Task?) {
        task?(true)
    }
    
    public init(time: TimeInterval) {
        self.time = time
    }

}
